﻿#include "amplprogramwindow.h"
#include "ui_amplprogramwindow.h"
#include <mainwindow.h>
extern intListener doorStatus;
amplprogramwindow::amplprogramwindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::amplprogramwindow)
{
    ui->setupUi(this);
    setWindowIcon(QIcon(":/pic/picture/kafavicon.ico"));
    QStringList  labels;
    labels <<QStringLiteral("ID")<<QStringLiteral("是否默认") << QStringLiteral("程序名称") << QStringLiteral("时长") << QStringLiteral("步骤数")<<QStringLiteral("创建时间")<<QStringLiteral("备注")<<QStringLiteral("操作");
    ui->tableWidget->setColumnCount(8);
    ui->tableWidget->setHorizontalHeaderLabels(labels);
    ui->tableWidget->resizeColumnsToContents(); //根据内容调整列宽
    ui->tableWidget->setColumnHidden(0, true); // 隐藏第1列
    ui->tableWidget->setColumnHidden(1, true); // 隐藏第1列
    ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget->setStyleSheet("background-color: rgb(235,243,255);");
    QHeaderView* headerView = ui->tableWidget->verticalHeader();
    headerView->setHidden(false); //false 显示行号列  true Hide
    ui->pushButton_5->setVisible(false);
}

//页面关闭时调用
amplprogramwindow::~amplprogramwindow()
{
    delete ui;
}

void amplprogramwindow::showEvent(QShowEvent *event){
    logClient = loghelper::getInstance();
    tcpClient = TcpClient::getInstance();

    RefreshTableData();
    event->accept();
}

void amplprogramwindow::on_addAmplStepBtn_clicked()
{
    this->hide();
    emit changeAmplStepWindow("");
}

//返回主页面
void amplprogramwindow::on_returnMainWinBtn_clicked()
{
    this->close();
    emit changeMainWindow();
}

//删除
void amplprogramwindow::delBtnClicked(){
    tcts *tctsWindow = new tcts();
    tctsWindow->infochange("提示","info","确认删除当前扩增程序",true,true);
    tctsWindow->show();

    QPushButton *btn = (QPushButton*)sender();
    QWidget *w_parent = (QWidget*)btn->parent();
    int x = w_parent->frameGeometry().x();
    int y = w_parent->frameGeometry().y();
    QModelIndex index = ui->tableWidget->indexAt(QPoint(x,y));
    rowNum=index.row();

    connect(tctsWindow->ui->pushButton_2, &QPushButton::clicked,[this](){
        QSqlDatabase db = dbHelper::openConnection();
        QSqlQuery query(db);

        QString id = ui->tableWidget->item(rowNum,0)->text();//取出当前行第1列内容
        QString sql=QString("Delete from AmplProgram where id='%1'").arg(id);
        query.exec(sql);

        sql=QString("Delete from AmplStep where ProgramId='%1'").arg(id);
        query.exec(sql);

        RefreshTableData();
    });
}

//设置默认
void amplprogramwindow::defaultBtnClicked(){

    QPushButton *btn = (QPushButton*)sender();
    QWidget *w_parent = (QWidget*)btn->parent();
    int x = w_parent->frameGeometry().x();
    int y = w_parent->frameGeometry().y();
    QModelIndex index = ui->tableWidget->indexAt(QPoint(x,y));
    rowNum=index.row();
    if(btn->text()=="取消默认")
    {
        tcts *tctsWindow = new tcts();
        tctsWindow->infochange("提示","info","是否取消默认程序",true,true);
        tctsWindow->show();
        connect(tctsWindow->ui->pushButton_2, &QPushButton::clicked,[this](){
            QSqlDatabase db = dbHelper::openConnection();
            QSqlQuery query(db);

            QString id=ui->tableWidget->item(rowNum,0)->text();
            QString sql=QString("Update AmplProgram set IsDefault='False' where id='%1'").arg(id);
            query.exec(sql);
            RefreshTableData();
        });
    }
    else{
        QString id=ui->tableWidget->item(rowNum,0)->text();
        QSqlDatabase db = dbHelper::openConnection();
        QSqlQuery query(db);
        QString sql=QString("Update AmplProgram set IsDefault='False'");
        query.exec(sql);

        sql=QString("Update AmplProgram set IsDefault='True' where id='%1'").arg(id);
        query.exec(sql);
        RefreshTableData();
    }
}

//点击查看按钮
void amplprogramwindow::viewBtnClicked(){
    QPushButton *btn = (QPushButton*)sender();
    QWidget *w_parent = (QWidget*)btn->parent();
    int x = w_parent->frameGeometry().x();
    int y = w_parent->frameGeometry().y();
    QModelIndex index = ui->tableWidget->indexAt(QPoint(x,y));

    QString id = ui->tableWidget->item(index.row(),0)->text();//取出当前行第1列内容
    this->hide();
    emit changeAmplStepReadWindow(id);
}

//刷新表格数据
void amplprogramwindow::RefreshTableData(){
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);

    ui->tableWidget->setRowCount(0);
    int rowNum=0;
    QList<QString> lableList;
    lableList<<"Id"<<"IsDefault"<<"ProgramName"<<"Duration"<<"StepNum"<<"CreateDate"<<"Memo";

    query.exec("Select * from AmplProgram");

    while (query.next()) {
        ui->tableWidget->insertRow(rowNum);

        QPushButton *delBtn = new QPushButton();
        delBtn->setText("删除");

        QPushButton *defaultBtn = new QPushButton();
        defaultBtn->setText("默认");

        QPushButton *viewBtn = new QPushButton();
        viewBtn->setText("查看");

        QWidget *tmp_widget = new QWidget();
        QHBoxLayout *tmp_layout = new QHBoxLayout(tmp_widget);

        tmp_layout->addWidget(delBtn);
        tmp_layout->addWidget(defaultBtn);
        tmp_layout->addWidget(viewBtn);
        tmp_layout->setMargin(0);
        ui->tableWidget->setCellWidget(rowNum,7,tmp_widget);

        connect(delBtn, SIGNAL(clicked()), this,SLOT(delBtnClicked()));
        connect(defaultBtn, SIGNAL(clicked()), this,SLOT(defaultBtnClicked()));
        connect(viewBtn, SIGNAL(clicked()), this,SLOT(viewBtnClicked()));

        if(query.value("IsDefault")=="True"){
            TriangleCornerLabel3 *label = new TriangleCornerLabel3();
            ui->tableWidget->setCellWidget(rowNum,2,label);
            label->setText(query.value("ProgramName").toString());
            defaultBtn->setText("取消默认");
            defaultBtn->setStyleSheet("background-color: rgb(173, 216, 230);");
        }

        for (int col = 0; col < lableList.length(); col++) {
            QTableWidgetItem *item = new QTableWidgetItem(query.value(lableList[col]).toString());
            item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
            ui->tableWidget->setItem(rowNum, col, item);
        }
        rowNum++;
    }
    query.clear();
}

//全部删除
void amplprogramwindow::on_pushButton_clicked()
{
    tcts *tctsWindow = new tcts();
    tctsWindow->infochange("提示","info","确认删除所有扩增程序",true,true);
    tctsWindow->show();

    connect(tctsWindow->ui->pushButton_2, &QPushButton::clicked,[this](){
        QSqlDatabase db = dbHelper::openConnection();
        QSqlQuery query(db);

        QString sql="Delete From AmplProgram";
        query.exec(sql);

        sql ="Delete From AmplStep";
        query.exec(sql);

        RefreshTableData();
    });
}

void TriangleCornerLabel3::paintEvent(QPaintEvent *event)
{
    QLabel::paintEvent(event);

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    // 设置三角形的颜色和样式
    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::darkBlue);

    // 计算三角形的顶点位置
    QPoint p1(this->width()-30, this->height()); // 左上角顶点
    QPoint p2(this->width(), this->height()); // 右上角顶点
    QPoint p3(this->width(), this->height()-30); // 左下角顶点

    // 绘制三角形
    QPainterPath path;
    path.moveTo(p1);
    path.lineTo(p2);
    path.lineTo(p3);
    path.closeSubpath();
    painter.drawPath(path);

    // 设置字体样式和大小
    painter.setPen(Qt::white); // 设置文本颜色为白色
    // 假设字体大小是三角形大小的一半（或根据需要调整）
    painter.setFont(QFont("Arial", 8, QFont::Bold));
    // 计算文本位置
    QPoint textTopLeft(this->width()-13,this->height()-7); // 确保文本在三角形内部并靠近上边缘
    // 绘制文本
    painter.drawText(textTopLeft, "默");
}

